package cn.lzm.serializer;


import cn.lizemin.entity.RpcRequest;
import cn.lizemin.entity.RpcResponse;
import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;

/**
 * @author lzm
 * @Date 2024/7/27
 * @description
 */
public class JsonSerializer implements Serializer {

    @SneakyThrows
    @Override
    public <T> byte[] serialize(T data) {
        return JSON.toJSONBytes(data);
    }

    @SneakyThrows
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        T obj = JSON.parseObject(data, clazz);
        if (obj instanceof RpcRequest) {
            RpcRequest request = (RpcRequest) obj;
            Object[] args = request.getArgs();
            Class<?>[] argTypes = request.getArgTypes();
            for (int i = 0; i < argTypes.length; i++) {
                Class<?> argType = argTypes[i];
                if (!argType.isAssignableFrom(args[i].getClass())) {
                    // 类型转换，将参数值转为对应的数据类型
                    byte[] bytes = JSON.toJSONBytes(args[i]);
                    args[i] = JSON.parseObject(bytes, argType);
                }
            }
            return clazz.cast(request);
        }
        if (obj instanceof RpcResponse) {
            RpcResponse response = (RpcResponse) obj;
            byte[] dataBytes = JSON.toJSONBytes(response.getData());
            response.setData(JSON.parseObject(dataBytes, response.getDataType()));
            return clazz.cast(response);
        }
        return null;
    }

}
